<?php
/*
 * 联系人
*/
class Contacter_model extends CI_Model {
	public function __construct() {
		parent :: __construct();
	}

	public function count_nums(){ /*取得总行数*/
		$user_id =$this->session->userdata('id');
		$role = $this->session->userdata('role');
		$username = $this->session->userdata('username');
		if($role == '市场'){
			$sql="SELECT count(*) as nums FROM (customer) JOIN contacter " .
					"ON customer.id = contacter.customer_id " .
					"WHERE customer.id " .
					"in (select id from customer where 1=1 and INSTR(`share`, '".$username."') or user_id = $user_id) ";
			$query = $this->db->query($sql);
			$row = $query->row_array();
			$count = $row['nums'];
		}else{
			$this->db->select('*');
			$this->db->from('customer');
			$this->db->join('contacter', 'customer.id = contacter.customer_id');
			$count = $this->db->count_all_results();
		}
		return $count;
	}

	public function list_contacters($limit,$offset = 0){ /*获取分页contacter数据*/
		/*获取登陆用户的user_id*/
		$user_id =$this->session->userdata('id');
		$role = $this->session->userdata('role');
		$username = $this->session->userdata('username');
		/*查询用户是否得到分享*/
		$sql="SELECT customer.id as customer_id, customer.customer_name as customer_name, customer.user_id as customer_user_id, customer.parent_id as parent_id, contacter.* " .
				" FROM (customer) JOIN contacter ON customer.id = contacter.customer_id " ;
		if($role == '市场'){
			$sql.=" WHERE customer.id in (select id from customer where 1=1 and INSTR(`share`, '".$username."') or user_id = $user_id) ";
		}
		if(!$offset){
			$sql.=" order by contacter.create_time desc "." LIMIT 0, $limit";
		}else{
			$sql.=" order by contacter.create_time desc "." LIMIT $offset, $limit";
		}
		$query = $this->db->query($sql);
		$contacters = $query->result();
// 		$con_count = count($contacters);
		
		/*查询所有的父级客户*/
// 		$all_parent_customers_query = $this->db->query("SELECT * FROM customer where parent_id = 0");
// 		$all_parent_customers = $all_parent_customers_query->result();
		
// 		$i=0;
// 		foreach ($all_parent_customers as $row_cus){
// 			$sql="SELECT customer.id as customer_id, customer.customer_name as customer_name, customer.user_id as customer_user_id, customer.parent_id as parent_id, contacter.* " .
// 				 "FROM (customer) JOIN contacter ON customer.id = contacter.customer_id  where parent_id = $row_cus->id or customer_id = $row_cus->id" ;
// 			$query = $this->db->query($sql);
// 			$children_customers = $query->result();
// 			$all_parent_customers[$i]->customers = $children_customers;
// 			$i++;
// 		}
// 		$contacters = $all_parent_customers;
		if ($query->num_rows() > 0){
			return $contacters;
		}else{
			return $contacters;
		}
	}
}
?>